<template>
  <div class="topic-workspace">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="header-left">
        <button @click="goHome" class="back-button">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M19 12H5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M12 19L5 12L12 5" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          返回首页
        </button>
        
        <!-- 主题信息 -->
        <div v-if="currentTopic" class="topic-header">
          <div class="topic-icon" :style="{ backgroundColor: currentTopic.color }">
            {{ currentTopic.icon || '📝' }}
          </div>
          <div class="topic-info">
            <h1>{{ currentTopic.title }}</h1>
            <p v-if="currentTopic.description">{{ currentTopic.description }}</p>
          </div>
        </div>
      </div>
      
      <div class="header-actions">

      </div>
    </div>
    
    <!-- 保存提示 -->
    <div v-if="saveMessage" class="save-message" :class="saveMessageType">
      {{ saveMessage }}
    </div>
    
    <!-- 主内容区域 -->
    <div class="main-container">
      <!-- 左侧文档树 -->
      <div class="sidebar">
        <div class="sidebar-header">
          <h3>目录</h3>
          <div class="sidebar-actions">
            <button @click="handleCreateNewFolder" class="icon-button" title="新建文件夹">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M10 4H4C2.89543 4 2 4.89543 2 6V18C2 19.1046 2.89543 20 4 20H20C21.1046 20 22 19.1046 22 18V8C22 6.89543 21.1046 6 20 6H12L10 4Z" stroke="currentColor" stroke-width="2"/>
              </svg>
            </button>
            <button @click="handleCreateNewDocument" class="icon-button" title="新建文档">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M14 2H6C4.89543 2 4 2.89543 4 4V20C4 21.1046 4.89543 22 6 22H18C19.1046 22 20 21.1046 20 20V8L14 2Z" stroke="currentColor" stroke-width="2"/>
              </svg>
            </button>
          </div>
        </div>
        
        <div class="sidebar-content">
          <div v-if="loading" class="loading">
            加载中...
          </div>
          <div v-else-if="!documentTree || documentTree.length === 0" class="empty-state">
            <p>该主题下暂无文档</p>
            <p>点击上方按钮创建新文档或文件夹</p>
          </div>
          <div v-else class="documents-tree">
            <DocumentTreeItem 
              v-for="item in documentTree" 
              :key="item.id" 
              :item="item"
              :depth="0"
              @open="openDocument"
              @move="handleMove"
              @delete="deleteDocument"
              @create-document="createNewDocument"
              @create-folder="createNewFolder"
            />
          </div>
        </div>
      </div>
      
      <!-- 右侧编辑区域和大纲 -->
      <div class="content-area">
        <div v-if="!selectedDocument" class="welcome-content">
          <div class="welcome-card">
            <div class="topic-icon-large" :style="{ backgroundColor: currentTopic?.color }">
              {{ currentTopic?.icon || '📝' }}
            </div>
            <h2>欢迎来到 {{ currentTopic?.title }}</h2>
            <p v-if="currentTopic?.description">{{ currentTopic.description }}</p>
            
            <div class="quick-actions">
              <button @click="handleCreateNewDocument" class="quick-action-button primary">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                  <path d="M14 2H6C4.89543 2 4 2.89543 4 4V20C4 21.1046 4.89543 22 6 22H18C19.1046 22 20 21.1046 20 20V8L14 2Z" stroke="currentColor" stroke-width="2"/>
                </svg>
                创建新文档
              </button>
              <button @click="handleCreateNewFolder" class="quick-action-button">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                  <path d="M10 4H4C2.89543 4 2 4.89543 2 6V18C2 19.1046 2.89543 20 4 20H20C21.1046 20 22 19.1046 22 18V8C22 6.89543 21.1046 6 20 6H12L10 4Z" stroke="currentColor" stroke-width="2"/>
                </svg>
                创建文件夹
              </button>
            </div>
            
            <!-- 统计信息 -->
            <div class="topic-stats">
              <div class="stat-item">
                <span class="stat-number">{{ documentCount }}</span>
                <span class="stat-label">文档数量</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ folderCount }}</span>
                <span class="stat-label">文件夹数量</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 文档编辑区域 -->
        <div v-else class="editor-container">
          <!-- 顶部工具栏 -->
          <div class="editor-toolbar">
            <div class="toolbar-left">
              <span class="document-title">{{ selectedDocument.title }}</span>
              <span class="document-status" :class="{ saving: isSaving, saved: !isSaving }">
                {{ isSaving ? '保存中...' : '已保存' }}
              </span>
            </div>
            
            <!-- 中间协作用户头像显示 -->
            <div class="toolbar-center">
              <div class="collaborators-container">
                <div class="collaborators-list">
                  <!-- 正在编辑的用户 -->
                  <div 
                    v-for="user in users.filter(u => u.status === 'editing')" 
                    :key="'editing-' + user.id" 
                    class="collaborator-avatar editing"
                    :style="{ borderColor: user.color }"
                    :title="user.name + ' (正在编辑)'"
                  >
                    <div class="avatar-content" :style="{ backgroundColor: user.color }">
                      {{ user.name.charAt(0) }}
                    </div>
                  </div>
                  
                  <!-- 正在查看的用户 -->
                  <div 
                    v-for="user in users.filter(u => u.status === 'viewing')" 
                    :key="'viewing-' + user.id" 
                    class="collaborator-avatar viewing"
                    :style="{ borderColor: user.color }"
                    :title="user.name + ' (正在查看)'"
                  >
                    <div class="avatar-content" :style="{ backgroundColor: user.color }">
                      {{ user.name.charAt(0) }}
                    </div>
                  </div>
                  
                  <!-- 最近查看过的用户 -->
                  <div 
                    v-for="user in users.filter(u => u.status === 'left').slice(0, 3)" 
                    :key="'left-' + user.id" 
                    class="collaborator-avatar left"
                    :style="{ borderColor: user.color }"
                    :title="user.name + ' (最近查看过)'"
                  >
                    <div class="avatar-content" :style="{ backgroundColor: user.color }">
                      {{ user.name.charAt(0) }}
                    </div>
                  </div>
                </div>
                
                <!-- 连接状态指示器 -->
                <div class="connection-indicator">
                  <span class="status-dot" :class="connectionStatus" :title="getConnectionStatusText()"></span>
                </div>
                
                <!-- 协同提示 -->
                <div v-if="connectionStatus === 'connected' && users.length <= 1" class="collaboration-tip">
                  <span class="tip-text">💬 要测试协同，请在新标签页打开Editor页面编辑同一文档</span>
                </div>
              </div>
            </div>
            <div class="toolbar-right">
              <button @click="openInEditor" class="toolbar-button editor-button" title="在Editor页面打开同一文档">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                  <path d="M18 13V19C18 19.5304 17.7893 20.0391 17.4142 20.4142C17.0391 20.7893 16.5304 21 16 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V8C3 7.46957 3.21071 6.96086 3.58579 6.58579C3.96086 6.21071 4.46957 6 5 6H11" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M15 3H21V9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <path d="M10 14L21 3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                在Editor中打开
              </button>
              <button @click="saveDocument" class="toolbar-button" :disabled="isSaving">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                  <path d="M19 21H5C3.89543 21 3 20.1046 3 19V5C3 3.89543 3.89543 3 5 3H16.1716C16.702 3 17.2107 3.21071 17.5858 3.58579L20.4142 6.41421C20.7893 6.78929 21 7.29799 21 7.82843V19C21 20.1046 20.1046 21 19 21Z" stroke="currentColor" stroke-width="2"/>
                </svg>
                保存
              </button>
              <button @click="closeDocument" class="toolbar-button">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                  <path d="M6 18L18 6M6 6L18 18" stroke="currentColor" stroke-width="2"/>
                </svg>
                关闭
              </button>
            </div>
          </div>
          
          <!-- 编辑器主体 -->
          <div class="editor-main">
            <!-- 中间编辑区 -->
            <div class="editor-content">
              <TiptapEditor 
                v-model="documentContent" 
                @update:modelValue="onEditorInput"
                ref="tiptapEditor"
              />
            </div>
            
            <!-- 右侧大纲 -->
            <div class="outline-sidebar">
              <!-- 协作用户信息 -->
              <div v-if="selectedDocument" class="collaboration-section">
                <div class="section-header" @click="toggleCollaboration">
                  <h3>协作用户</h3>
                  <div class="connection-status">
                    <span class="status-dot" :class="connectionStatus"></span>
                    <span class="collapse-toggle">{{ isCollaborationCollapsed ? '+' : '-' }}</span>
                  </div>
                </div>
                <div v-show="!isCollaborationCollapsed" class="collaboration-content">
                  <div class="collaboration-info">
                    <!-- 正在编辑的用户 -->
                    <div class="user-category">
                      <h4>正在编辑:</h4>
                      <div v-for="user in users.filter(u => u.status === 'editing')" :key="user.id" class="user" :style="{ color: user.color }">
                        {{ user.name }}
                        <span v-if="user.id === currentUserId">(您)</span>
                      </div>
                      <div v-if="users.filter(u => u.status === 'editing').length === 0" class="no-users">暂无用户正在编辑</div>
                    </div>
                    
                    <!-- 正在查看的用户 -->
                    <div class="user-category">
                      <h4>正在查看:</h4>
                      <div v-for="user in users.filter(u => u.status === 'viewing')" :key="user.id" class="user" :style="{ color: user.color }">
                        {{ user.name }}
                        <span v-if="user.id === currentUserId">(您)</span>
                      </div>
                      <div v-if="users.filter(u => u.status === 'viewing').length === 0" class="no-users">暂无用户正在查看</div>
                    </div>
                    
                    <!-- 已离开的用户 -->
                    <div class="user-category">
                      <h4>最近查看过:</h4>
                      <div v-for="user in users.filter(u => u.status === 'left')" :key="user.id" class="user left-user" :style="{ color: user.color }">
                        {{ user.name }}
                      </div>
                      <div v-if="users.filter(u => u.status === 'left').length === 0" class="no-users">暂无用户记录</div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 文档大纲 -->
              <div class="outline-header">
                <h3>文档大纲</h3>
                <button @click="toggleOutline" class="outline-toggle">
                  {{ isOutlineCollapsed ? '展开' : '收起' }}
                </button>
              </div>
              <div v-show="!isOutlineCollapsed" class="outline-content">
                <div v-if="documentOutline.length > 0" class="outline-list">
                  <div 
                    v-for="(item, index) in documentOutline" 
                    :key="index" 
                    :class="`outline-item outline-${item.level}`"
                    @click="scrollToHeading(item.id)"
                  >
                    {{ item.text }}
                  </div>
                </div>
                <div v-else class="outline-empty">
                  <p>暂无大纲</p>
                  <small>添加标题后将自动生成大纲</small>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import DocumentTreeItem from '../components/DocumentTreeItem.vue'
import TiptapEditor from '../components/TiptapEditor.vue'

interface Document {
  id: number
  title: string
  content?: string
  type: 'document' | 'folder'
  parent_id?: number
  topic_id?: number
  sort_order: number
  created_at: string
  updated_at: string
  children?: Document[]
}

interface Topic {
  id: number
  title: string
  description?: string
  color: string
  icon?: string
  created_by?: number
  is_default: boolean
  sort_order: number
  created_at: string
  updated_at: string
}

interface User {
  id: string
  name: string
  color: string
  cursor?: { x: number; y: number }
  selection?: string
  status: 'viewing' | 'editing' | 'left'
  lastActive: Date
  documentId?: number
}

const router = useRouter()
const route = useRoute()

const topicId = ref<number>(parseInt(route.params.topicId as string))
const currentTopic = ref<Topic | null>(null)
const documentTree = ref<Document[]>([])
const selectedDocument = ref<Document | null>(null)
const documentContent = ref('')
const loading = ref(true)
const currentUser = ref<any>(null)
const saveMessage = ref('')
const saveMessageType = ref<'success' | 'error'>('success')

// 编辑器相关状态
const isSaving = ref(false)
const isOutlineCollapsed = ref(false)
const documentOutline = ref<any[]>([])
const tiptapEditor = ref<any>(null)

// 协同功能相关
const connectionStatus = ref<'disconnected' | 'connecting' | 'connected'>('disconnected')
const users = ref<Array<User>>([])
const currentUserId = ref('')
const userName = ref('')
const userNameSet = ref(true)
const isCollaborationCollapsed = ref(false)

// WebSocket连接
let socket: WebSocket | null = null
let lastEditTime: number | null = null
let editTimeout: number | null = null
let saveTimeout: number | null = null

// 计算统计信息
const documentCount = computed(() => {
  const countDocuments = (items: Document[]): number => {
    return items.reduce((count, item) => {
      if (item.type === 'document') count++
      if (item.children) count += countDocuments(item.children)
      return count
    }, 0)
  }
  return countDocuments(documentTree.value)
})

const folderCount = computed(() => {
  const countFolders = (items: Document[]): number => {
    return items.reduce((count, item) => {
      if (item.type === 'folder') count++
      if (item.children) count += countFolders(item.children)
      return count
    }, 0)
  }
  return countFolders(documentTree.value)
})

// 获取当前用户
const getCurrentUser = () => {
  const user = localStorage.getItem('user')
  if (user) {
    try {
      currentUser.value = JSON.parse(user)
      userName.value = currentUser.value.username || ''
      currentUserId.value = 'user_' + currentUser.value.id
    } catch (e) {
      console.error('Failed to parse user from localStorage:', e)
      currentUser.value = null
    }
  }
}

// 协同功能方法
// 从localStorage获取用户信息
const getUserInfoFromStorage = () => {
  const user = localStorage.getItem('user')
  if (user) {
    try {
      const userData = JSON.parse(user)
      userName.value = userData.username || ''
      currentUserId.value = 'user_' + userData.id
    } catch (e) {
      console.error('Error parsing user data:', e)
    }
  }
}

// 生成随机颜色
const getRandomColor = () => {
  const colors = [
    '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF',
    '#FFA500', '#800080', '#008000', '#000080', '#800000', '#808000'
  ]
  return colors[Math.floor(Math.random() * colors.length)]
}

// 发送用户活动更新
const sendUserActivity = (activity: 'viewing' | 'editing') => {
  if (socket && socket.readyState === WebSocket.OPEN && selectedDocument.value) {
    const userUpdateMessage = {
      type: 'user-update',
      user: {
        id: currentUserId.value,
        status: activity,
        lastActive: new Date(),
        documentId: selectedDocument.value.id
      }
    }
    console.log('Sending user activity update:', userUpdateMessage)
    socket.send(JSON.stringify(userUpdateMessage))
  }
}

// 连接到WebSocket服务器
const connect = () => {
  if (!userName.value || !selectedDocument.value) {
    console.log('Missing required info for connection')
    return
  }
  
  console.log('Attempting to connect to WebSocket server with:', { 
    userName: userName.value, 
    currentUserId: currentUserId.value, 
    documentId: selectedDocument.value.id 
  })
  connectionStatus.value = 'connecting'
  
  // 连接到WebSocket服务器
  socket = new WebSocket('ws://localhost:3000')
  
  socket.onopen = () => {
    console.log('Connected to WebSocket server')
    connectionStatus.value = 'connected'
    
    // 发送用户加入消息
    if (socket && selectedDocument.value) {
      const userJoinMessage = {
        type: 'user-join',
        user: { 
          id: currentUserId.value, 
          name: userName.value, 
          color: getRandomColor(),
          documentId: selectedDocument.value.id,
          status: 'viewing',
          lastActive: new Date()
        }
      }
      console.log('Sending user-join message:', userJoinMessage)
      socket.send(JSON.stringify(userJoinMessage))
      
      // 将当前用户添加到用户列表中
      users.value.push({
        id: currentUserId.value,
        name: userName.value,
        color: getRandomColor(),
        documentId: selectedDocument.value.id,
        status: 'viewing',
        lastActive: new Date()
      })
    }
  }
  
  socket.onmessage = (event) => {
    let data: any
    try {
      data = JSON.parse(event.data)
    } catch (e) {
      console.error('Error parsing WebSocket message:', e)
      return
    }
    
    console.log('TopicWorkspace - Received WebSocket message:', data)
    console.log('TopicWorkspace - Current document:', selectedDocument.value ? selectedDocument.value.id : 'none')
    
    // 只处理当前文档的消息
    if (data.documentId !== undefined && selectedDocument.value && data.documentId !== selectedDocument.value.id) {
      console.log('TopicWorkspace - Ignoring message for different document:', data.documentId, 'vs', selectedDocument.value.id)
      return
    }
    
    switch (data.type) {
      case 'connected':
        console.log('WebSocket connection confirmed')
        break
        
      case 'document-update':
        console.log('TopicWorkspace - Processing document-update, content length:', data.content?.length)
        // 更新编辑器内容
        documentContent.value = data.content
        updateDocumentOutline()
        console.log('TopicWorkspace - Updated document content')
        break
        
      case 'user-join':
        // 添加新用户
        if (data.user && !users.value.find(u => u.id === data.user.id)) {
          users.value.push({
            ...data.user,
            status: data.user.status || 'viewing',
            lastActive: data.user.lastActive ? new Date(data.user.lastActive) : new Date()
          })
        }
        break
        
      case 'user-update':
        // 更新用户信息
        if (data.user) {
          const existingUserIndex = users.value.findIndex(u => u.id === data.user.id)
          if (existingUserIndex !== -1) {
            users.value[existingUserIndex] = {
              ...users.value[existingUserIndex],
              ...data.user,
              status: data.user.status || 'viewing',
              lastActive: data.user.lastActive ? new Date(data.user.lastActive) : new Date()
            }
          } else {
            users.value.push({
              ...data.user,
              status: data.user.status || 'viewing',
              lastActive: data.user.lastActive ? new Date(data.user.lastActive) : new Date()
            })
          }
        }
        console.log('Updated users list:', users.value)
        break
        
      case 'user-leave':
        // 更新用户状态为已离开
        const leavingUserIndex = users.value.findIndex(u => u.id === data.user.id)
        if (leavingUserIndex !== -1) {
          users.value[leavingUserIndex].status = 'left'
          users.value[leavingUserIndex].lastActive = new Date()
        }
        break
        
      default:
        console.log('Unknown message type:', data.type)
    }
  }
  
  socket.onclose = (event) => {
    console.log('Disconnected from WebSocket server', event)
    connectionStatus.value = 'disconnected'
    
    // 清除定时器
    if (editTimeout) {
      clearTimeout(editTimeout)
      editTimeout = null
    }
  }
  
  socket.onerror = (error) => {
    console.error('WebSocket error:', error)
    connectionStatus.value = 'disconnected'
    
    // 清除定时器
    if (editTimeout) {
      clearTimeout(editTimeout)
      editTimeout = null
    }
  }
}

// 切换协作信息展开/收缩
const toggleCollaboration = () => {
  isCollaborationCollapsed.value = !isCollaborationCollapsed.value
}

// 获取连接状态文本
const getConnectionStatusText = () => {
  switch (connectionStatus.value) {
    case 'connected': return '已连接'
    case 'connecting': return '连接中'
    case 'disconnected': return '已断开'
    default: return '未知状态'
  }
}

// 返回首页
const goHome = () => {
  router.push('/')
}

// 加载主题信息
const loadTopic = async () => {
  try {
    const response = await fetch('http://localhost:3000/api/topics')
    const data = await response.json()
    
    if (response.ok) {
      const topic = data.topics.find((t: Topic) => t.id === topicId.value)
      if (topic) {
        currentTopic.value = topic
      } else {
        console.error('Topic not found')
        router.push('/')
      }
    } else {
      console.error('Failed to load topics:', data.error)
      router.push('/')
    }
  } catch (err) {
    console.error('Load topic error:', err)
    router.push('/')
  }
}

// 加载该主题下的文档列表
const loadDocuments = async () => {
  if (!currentUser.value) {
    loading.value = false
    return
  }
  
  console.log('Loading documents for user:', currentUser.value.id, 'topic:', topicId.value)
  
  try {
    const response = await fetch(`http://localhost:3000/api/documents/user/${currentUser.value.id}/topic/${topicId.value}/tree`)
    const data = await response.json()
    
    console.log('API response:', response.ok, data)
    
    if (response.ok && data && Array.isArray(data.tree)) {
      documentTree.value = data.tree
      console.log('Documents loaded:', data.tree)
    } else {
      documentTree.value = []
      console.log('No documents found or invalid response')
    }
  } catch (err) {
    console.error('Load documents error:', err)
    documentTree.value = []
  } finally {
    loading.value = false
  }
}

// 创建新文档
const createNewDocument = async (parentId?: number) => {
  if (!currentUser.value) return
  
  try {
    const response = await fetch('http://localhost:3000/api/documents', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: '新文档 ' + new Date().toLocaleString(),
        content: '',
        type: 'document',
        parent_id: parentId,
        owner_id: currentUser.value.id,
        topic_id: topicId.value
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      saveMessage.value = '文档创建成功！'
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      
      // 重新加载文档列表
      await loadDocuments()
      
      // 自动打开新创建的文档
      const newDocument: Document = {
        id: data.document.id,
        title: data.document.title,
        type: 'document',
        content: data.document.content || '',
        sort_order: 0,
        created_at: '',
        updated_at: ''
      }
      await openDocument(newDocument)
    } else {
      console.error('Failed to create document:', data.error)
      showError('文档创建失败：' + (data.error || '未知错误'))
    }
  } catch (err) {
    console.error('Create document error:', err)
    showError('文档创建失败：网络错误')
  }
}

// 创建新文件夹
const createNewFolder = async (parentId?: number) => {
  if (!currentUser.value) return
  
  const folderName = prompt('请输入文件夹名称:', '新文件夹')
  if (!folderName) return
  
  try {
    const response = await fetch('http://localhost:3000/api/documents', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: folderName,
        type: 'folder',
        parent_id: parentId,
        owner_id: currentUser.value.id,
        topic_id: topicId.value
      })
    })
    
    const data = await response.json()
    
    if (response.ok) {
      saveMessage.value = '文件夹创建成功！'
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      
      // 重新加载文档列表
      loadDocuments()
    } else {
      console.error('Failed to create folder:', data.error)
      showError('文件夹创建失败：' + (data.error || '未知错误'))
    }
  } catch (err) {
    console.error('Create folder error:', err)
    showError('文件夹创建失败：网络错误')
  }
}

// 包装事件处理函数
const handleCreateNewDocument = () => createNewDocument()
const handleCreateNewFolder = () => createNewFolder()

// 打开文档
const openDocument = async (item: Document) => {
  if (item.type === 'document') {
    try {
      const response = await fetch(`http://localhost:3000/api/documents/${item.id}`)
      const data = await response.json()
      
      if (response.ok) {
        selectedDocument.value = item
        documentContent.value = data.document.content || ''
        updateDocumentOutline()
        
        // 清空之前的用户列表（切换文档时）
        users.value = []
        
        // 连接WebSocket实现协同编辑
        if (userName.value) {
          console.log('Connecting to WebSocket for document collaboration')
          connect()
        }
        
        // 发送查看状态
        setTimeout(() => {
          sendUserActivity('viewing')
        }, 500)
      } else {
        showError('文档加载失败')
      }
    } catch (err) {
      console.error('Load document error:', err)
      showError('文档加载失败：网络错误')
    }
  }
}

// 移动文档
const handleMove = (event: { itemId: number, newParentId?: number }) => {
  moveDocument(event.itemId, event.newParentId)
}

const moveDocument = async (itemId: number, newParentId?: number) => {
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${itemId}/move`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        parent_id: newParentId
      })
    })
    
    if (response.ok) {
      saveMessage.value = '移动成功！'
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      loadDocuments()
    } else {
      const data = await response.json()
      showError('移动失败：' + (data.error || '未知错误'))
    }
  } catch (err) {
    console.error('Move document error:', err)
    showError('移动失败：网络错误')
  }
}

// 删除文档/文件夹
const deleteDocument = async (item: Document) => {
  const confirmMessage = item.type === 'folder' 
    ? `确定要删除文件夹 "${item.title}" 及其所有内容吗？`
    : `确定要删除文档 "${item.title}" 吗？`
  
  if (!confirm(confirmMessage)) return
  
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${item.id}`, {
      method: 'DELETE'
    })
    
    if (response.ok) {
      saveMessage.value = `${item.type === 'folder' ? '文件夹' : '文档'}删除成功！`
      saveMessageType.value = 'success'
      setTimeout(() => {
        saveMessage.value = ''
      }, 3000)
      loadDocuments()
    } else {
      const data = await response.json()
      showError(`删除失败：${data.error || '未知错误'}`)
    }
  } catch (err) {
    console.error('Delete document error:', err)
    showError('删除失败：网络错误')
  }
}

// 显示错误信息
const showError = (message: string) => {
  saveMessage.value = message
  saveMessageType.value = 'error'
  setTimeout(() => {
    saveMessage.value = ''
  }, 3000)
}

// 编辑器相关方法
const onEditorInput = (content: string) => {
  documentContent.value = content
  
  // 发送内容更新到服务器
  if (socket && socket.readyState === WebSocket.OPEN && selectedDocument.value) {
    socket.send(JSON.stringify({
      type: 'document-update',
      content: documentContent.value,
      documentId: selectedDocument.value.id
    }))
    
    // 更新用户状态为正在编辑
    sendUserActivity('editing')
    
    // 记录最后编辑时间
    lastEditTime = Date.now()
    
    // 清除之前的定时器
    if (editTimeout) {
      clearTimeout(editTimeout)
    }
    
    // 设置定时器，在用户停止编辑2秒后将其状态改回查看
    editTimeout = window.setTimeout(() => {
      if (lastEditTime && Date.now() - lastEditTime >= 2000) {
        sendUserActivity('viewing')
        lastEditTime = null
      }
    }, 2000)
  }
  
  updateDocumentOutline()
  // 自动保存（防抖）
  if (saveTimeout) clearTimeout(saveTimeout)
  saveTimeout = setTimeout(saveDocument, 2000)
}

const saveDocument = async () => {
  if (!selectedDocument.value || isSaving.value) return
  
  isSaving.value = true
  try {
    const response = await fetch(`http://localhost:3000/api/documents/${selectedDocument.value.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: selectedDocument.value.title,
        content: documentContent.value
      })
    })
    
    if (response.ok) {
      // 静默保存，不显示提示
    } else {
      showError('保存失败')
    }
  } catch (err) {
    console.error('Save document error:', err)
    showError('保存失败：网络错误')
  } finally {
    isSaving.value = false
  }
}

const closeDocument = () => {
  if (saveTimeout) {
    clearTimeout(saveTimeout)
  }
  
  // 断开WebSocket连接
  if (socket) {
    // 发送用户离开消息
    if (socket.readyState === WebSocket.OPEN) {
      socket.send(JSON.stringify({
        type: 'user-leave',
        user: { id: currentUserId.value }
      }))
    }
    socket.close()
    socket = null
  }
  
  // 清除定时器
  if (editTimeout) {
    clearTimeout(editTimeout)
    editTimeout = null
  }
  
  selectedDocument.value = null
  documentContent.value = ''
  documentOutline.value = []
  users.value = []
  connectionStatus.value = 'disconnected'
}

// 在Editor中打开当前文档
const openInEditor = () => {
  if (selectedDocument.value) {
    const editorUrl = `/editor?id=${selectedDocument.value.id}`
    window.open(editorUrl, '_blank')
  }
}

const toggleOutline = () => {
  isOutlineCollapsed.value = !isOutlineCollapsed.value
}

const updateDocumentOutline = () => {
  // 从编辑器内容中提取标题生成大纲
  const headings = extractHeadings(documentContent.value)
  documentOutline.value = headings
}

const extractHeadings = (content: string) => {
  const headings: any[] = []
  // 简单的标题提取逻辑，匹配 h1-h6 标签
  const headingRegex = /<h([1-6])[^>]*id="([^"]*)">([^<]+)<\/h[1-6]>/g
  let match
  
  while ((match = headingRegex.exec(content)) !== null) {
    headings.push({
      level: parseInt(match[1]),
      id: match[2] || `heading-${headings.length}`,
      text: match[3]
    })
  }
  
  return headings
}

const scrollToHeading = (headingId: string) => {
  if (tiptapEditor.value) {
    const element = tiptapEditor.value.$el?.querySelector(`#${headingId}`)
    if (element) {
      element.scrollIntoView({ behavior: 'smooth' })
    }
  }
}

onMounted(() => {
  getCurrentUser()
  getUserInfoFromStorage() // 获取用户信息用于协同功能
  loadTopic()
  loadDocuments()
  
  // 页面离开时保存
  window.addEventListener('beforeunload', () => {
    if (saveTimeout) {
      clearTimeout(saveTimeout)
      saveDocument()
    }
  })
})

onUnmounted(() => {
  console.log('TopicWorkspaceView unmounted')
  // 断开WebSocket连接
  if (socket) {
    // 发送用户离开消息
    if (socket.readyState === WebSocket.OPEN) {
      socket.send(JSON.stringify({
        type: 'user-leave',
        user: { id: currentUserId.value }
      }))
    }
    socket.close()
  }
  
  // 清除定时器
  if (editTimeout) {
    clearTimeout(editTimeout)
    editTimeout = null
  }
  
  if (saveTimeout) {
    clearTimeout(saveTimeout)
    // 保存文档
    saveDocument()
  }
})
</script>

<style scoped>
.topic-workspace {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

/* 顶部标题栏 */
.header {
  background: white;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: none;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
  transition: all 0.3s;
}

.back-button:hover {
  background: #f5f5f5;
  color: #333;
}

.topic-header {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.topic-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: white;
}

.topic-info h1 {
  margin: 0;
  color: #333;
  font-size: 1.5rem;
}

.topic-info p {
  margin: 0.25rem 0 0 0;
  color: #666;
  font-size: 0.9rem;
}

.header-actions {
  display: flex;
  gap: 0.5rem;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s;
}

.folder-button {
  background: #ff9800;
  color: white;
}

.folder-button:hover {
  background: #f57c00;
}

.document-button {
  background: #42b983;
  color: white;
}

.document-button:hover {
  background: #359c6d;
}

/* 保存提示 */
.save-message {
  padding: 10px;
  text-align: center;
  font-weight: bold;
}

.save-message.success {
  background-color: #4caf50;
  color: white;
}

.save-message.error {
  background-color: #f44336;
  color: white;
}

/* 主内容区域 */
.main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧边栏 */
.sidebar {
  width: 350px;
  background: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  color: #333;
  font-size: 1.1rem;
}

.sidebar-actions {
  display: flex;
  gap: 0.5rem;
}

.icon-button {
  width: 32px;
  height: 32px;
  border: 1px solid #ddd;
  background: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  transition: all 0.3s;
}

.icon-button:hover {
  background: #f5f5f5;
  color: #333;
  border-color: #ccc;
}

.sidebar-content {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
}

.loading, .empty-state {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.empty-state p {
  margin: 0.5rem 0;
}

.documents-tree {
  display: flex;
  flex-direction: column;
}

/* 右侧内容区域 */
.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

/* 欢迎页面 */
.welcome-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

/* 编辑器容器 */
.editor-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.document-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
}

.document-status {
  font-size: 0.9rem;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
}

.document-status.saving {
  background: #fff3cd;
  color: #856404;
}

.document-status.saved {
  background: #d4edda;
  color: #155724;
}

.toolbar-right {
  display: flex;
  gap: 0.5rem;
}

.toolbar-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s;
}

.toolbar-button:hover:not(:disabled) {
  background: #f5f5f5;
  border-color: #ccc;
}

.toolbar-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 编辑器主体 */
.editor-main {
  flex: 1;
  display: flex;
  min-height: 0;
}

.editor-content {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
  background: white;
}

/* 右侧大纲 */
.outline-sidebar {
  width: 280px;
  background: #f8f9fa;
  border-left: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
}

.outline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e0e0e0;
  background: white;
}

.outline-header h3 {
  margin: 0;
  font-size: 1rem;
  color: #333;
}

.outline-toggle {
  padding: 0.25rem 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  font-size: 0.8rem;
}

.outline-toggle:hover {
  background: #f5f5f5;
}

.outline-content {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
}

.outline-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.outline-item {
  padding: 0.5rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 0.9rem;
}

.outline-item:hover {
  background: #e9ecef;
}

.outline-item.outline-1 {
  font-weight: 600;
  color: #333;
}

.outline-item.outline-2 {
  padding-left: 1rem;
  color: #555;
}

.outline-item.outline-3 {
  padding-left: 1.5rem;
  color: #666;
  font-size: 0.85rem;
}

.outline-item.outline-4,
.outline-item.outline-5,
.outline-item.outline-6 {
  padding-left: 2rem;
  color: #777;
  font-size: 0.8rem;
}

.outline-empty {
  text-align: center;
  color: #666;
  padding: 2rem 1rem;
}

.outline-empty p {
  margin: 0 0 0.5rem 0;
}

.outline-empty small {
  color: #999;
}

.welcome-card {
  background: white;
  padding: 3rem 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.topic-icon-large {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  color: white;
  margin: 0 auto 1.5rem;
}

.welcome-card h2 {
  margin: 0 0 1rem 0;
  color: #333;
  font-size: 1.8rem;
}

.welcome-card p {
  color: #666;
  margin-bottom: 2rem;
  font-size: 1.1rem;
}

.quick-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
  margin-bottom: 2rem;
}

.quick-action-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 1rem;
}

.quick-action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.quick-action-button.primary {
  background: #42b983;
  color: white;
  border-color: #42b983;
}

.quick-action-button.primary:hover {
  background: #359c6d;
}

.topic-stats {
  display: flex;
  gap: 2rem;
  justify-content: center;
  padding-top: 2rem;
  border-top: 1px solid #e0e0e0;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 2rem;
  font-weight: bold;
  color: #42b983;
}

.stat-label {
  color: #666;
  font-size: 0.9rem;
}

/* 协作功能样式 */
/* 协作用户头像 */
.collaborators-container {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.collaborators-list {
  display: flex;
  gap: 0.25rem;
}

.collaborator-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 2px solid;
  position: relative;
  transition: all 0.3s;
}

.collaborator-avatar.editing {
  border-width: 3px;
  animation: pulse 2s infinite;
}

.collaborator-avatar.viewing {
  border-width: 2px;
  opacity: 0.8;
}

.collaborator-avatar.left {
  border-width: 1px;
  opacity: 0.5;
}

.avatar-content {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 0.75rem;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

/* 连接状态指示器 */
.connection-indicator {
  display: flex;
  align-items: center;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-left: 0.5rem;
}

.status-dot.connected {
  background-color: #4caf50;
  animation: connected-pulse 2s infinite;
}

.status-dot.connecting {
  background-color: #ff9800;
  animation: connecting-blink 1s infinite;
}

.status-dot.disconnected {
  background-color: #f44336;
}

@keyframes connected-pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

@keyframes connecting-blink {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
  100% {
    opacity: 1;
  }
}

/* 协作用户信息侧边栏 */
.collaboration-section {
  border-bottom: 1px solid #e0e0e0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  cursor: pointer;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.section-header:hover {
  background: #f8f9fa;
}

.section-header h3 {
  margin: 0;
  font-size: 1rem;
  color: #333;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.collapse-toggle {
  font-weight: bold;
  color: #666;
}

.collaboration-content {
  background: #f8f9fa;
}

.collaboration-info {
  padding: 1rem;
}

.user-category {
  margin-bottom: 1rem;
}

.user-category:last-child {
  margin-bottom: 0;
}

.user-category h4 {
  margin: 0 0 0.5rem 0;
  font-size: 0.9rem;
  color: #555;
  font-weight: 600;
}

.user {
  padding: 0.25rem 0.5rem;
  margin: 0.25rem 0;
  border-radius: 4px;
  font-size: 0.85rem;
  font-weight: 500;
  background: rgba(255, 255, 255, 0.7);
}

.user.left-user {
  opacity: 0.7;
  font-style: italic;
}

.no-users {
  color: #999;
  font-size: 0.8rem;
  font-style: italic;
  padding: 0.25rem 0;
}

/* 工具栏中间区域 */
.toolbar-center {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 协同提示 */
.collaboration-tip {
  margin-left: 15px;
  padding: 4px 8px;
  background-color: #e3f2fd;
  border: 1px solid #2196f3;
  border-radius: 4px;
  font-size: 12px;
  color: #1976d2;
  white-space: nowrap;
}

.tip-text {
  font-size: 12px;
}

/* Editor按钮 */
.editor-button {
  background-color: #2196f3 !important;
  color: white !important;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.editor-button:hover {
  background-color: #1976d2 !important;
}

.editor-button:disabled {
  background-color: #ccc !important;
  color: #999 !important;
}
</style>